import globalConfig from '../configs/index.js'
import API from './api.js';
import {commonRequestHandle, filterData, requestHeader} from './config.js'

var commonHandle;

var httpRequest = method => (url, data, config) => {
    if (typeof url === 'function') {
        url = url(globalConfig.baseUrl);
    } else {
        url = globalConfig.baseUrl + url;
    }
    data = filterData(data);
    console.log('请求数据:', url, data, config);

    return new Promise(function (resolve, reject) {
        wx.request({
            url,
            data,
            method: method.toUpperCase(),
            header: requestHeader(data, config),
            dataType: 'json',  // 默认
            success: commonHandle = (...args) => {
                let temp = commonRequestHandle(...args);
                // 如果是系统错误,  拦截且不需要回调
                if (temp === -1) return;
                if (temp) resolve(...args);
                else reject(...args);
            },
            fail: commonHandle
        })
    })

}
export var ajaxRequest = {
    API,
    get: httpRequest('get'),
    post: httpRequest('post'),
}

export default ajaxRequest;
